<?php
use \Phalcon\Mvc\View;

class OauthController extends \Phalcon\Mvc\Controller
{


	public function indexAction()
	{
		echo "欢迎使用质量工程开放数据平台，请查阅文档使用！";
    }

	public function tokenAction()
	{
		$oauthServer=new OauthServer();
		$server = $oauthServer->getServerInstance();
		$server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();
	}

	public function authorizeAction()
	{
		
		$oauthServer=new OauthServer();
		$server = $oauthServer->getServerInstance();
		$request = OAuth2\Request::createFromGlobals();
		$response = new OAuth2\Response();
		// validate the authorize request
		if (!$server->validateAuthorizeRequest($request, $response)) {
		    $response->send();
		    die();
		}

		$clientDetail = $server->getClientDetail($this->request->get("client_id"));

		$scopes = $this->request->get("scope");
		if($scopes)
		{
			$scope_arr = explode(" ",$scopes);
			$this->view->setVar("scope_arr",$scope_arr);
			$this->view->setVar("scope_meaning",$this->apc->get("scope_meaning"));
		}

		/*
		*如果输入了用户名与密码，进行验证
		*/
		$result = "";
		// $user_id=false;
		if($this->request->isPost() == true){
			$user_id = $this->request->getPost("userid");
			$pwd = $this->request->getPost("pwd");
			$conditions = " email = :user_id: AND teacher_pwd = :pwd:";
			$parameters = array(
				"user_id" =>$user_id,
				"pwd" => md5($pwd)
				);

			$teacher = OdpTeacher::findFirst(array($conditions,"bind"=>$parameters));
			if($teacher){
				$is_authorized = true;
				if($server->handleAuthorizeRequest($request, $response, $is_authorized,$teacher->teacher_id)){
					$response->send();
				}
			}else{
				//验证错误错误处理
				$result = 'NO_USER';//默认无用户

				$c = " email = :user_id:";
				$param  =array("user_id"=>$user_id);
				$t = OdpTeacher::findFirst(array($c,"bind"=>$param));
				if($t){
					$result = "WRONG_PWD";
				}

			}
		}

		//需要使用验证图片
		$this->session->set("CAPTCHA_IMG","enabled");

		$this->assets
			->addCss('public/css/bootstrap/3.2.0/css/bootstrap.min.css')
			->addCss('public/css/ace/ace.min.css')
			->addCss('public/css/ace/ace-rtl.min.css')
			->addCss('public/css/style.css');

		$this->assets
			->addJs('public/js/jquery/jquery-2.1.1.min.js')
			->addJs('public/js/bootstrap/3.2.0/bootstrap.min.js')
			->addJs('public/js/angular/1.2.19/angular.min.js')
			->addJs('public/js/angular-strap/angular-strap.min.js')
			->addJs('public/js/angular-strap/angular-strap.tpl.min.js')
			->addJS('public/js/loginform.js')	
			->addJs('public/angular/controller/loginController.js')
			->addJs('public/angular/controller/forgotController.js')
		;

		$this->view->setVar("title","应用授权");
		$this->view->setVar("client_name",$clientDetail['client_name']);
		// $this->view->setVar("from",$redirect_uri);
		$this->view->setVar("user_id",$user_id);
		$this->view->setVar("result",$result);
		$this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
		$this->view->render('oauth','authorize');

	}
}

